<template>
  <div class="finance-page">
    <!-- 顶部固定 -->
    <div class="finance-header">
      <TopNavBar :title="_t18('15_title')" type="back" />
      <div class="asset-card">
        <div class="asset-header">
          <img
            class="coin-icon"
            src="https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1e8deac3f3e547629a8bf2b466dc0359.png"
          />
          <span class="coin-title">USD</span>
        </div>
        <div class="asset-balance">
          <span class="label">{{ _t18('15_available') }}</span>
          <span class="value">
            {{ total_zichan.toLocaleString() }}
            <span class="unit">USD</span>
          </span>
        </div>
      </div>

      <!-- Tabs -->
      <div class="record-section">
        <div class="record-title">{{ _t18('15_recordTitle') }}</div>
        <div class="tabs">
          <div :class="['tab-btn', activeTab === 0 ? 'active' : '']" @click="change(0)">
            {{ _t18('15_tab1') }}
            <div v-if="activeTab === 0" class="tab-arrow"></div>
          </div>
          <div :class="['tab-btn', activeTab === 1 ? 'active' : '']" @click="change(1)">
            {{ _t18('15_tab2') }}
            <div v-if="activeTab === 1" class="tab-arrow"></div>
          </div>
          <div :class="['tab-btn', activeTab === 2 ? 'active' : '']" @click="change(2)">
            {{ _t18('15_tab3') }}
            <div v-if="activeTab === 2" class="tab-arrow"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 滚动区域 -->
    <div class="finance-scroll">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="_t18('15_finished')"
        @load="onLoad"
      >
        <div v-if="getCurrentList.length === 0 && !loading" class="empty-box">
          <img
            class="empty-icon"
            src="/static/img/W2k_c7838bd9_spH.cd0c5744.png"
          />
          <div class="empty-text">{{ _t18('15_empty') }}</div>
        </div>

        <div v-else class="record-list">
          <!-- ✅ 充值 tab 保持你原先的样式 + 点击跳转 -->
          <template v-if="activeTab === 1">
            <div
              v-for="(item, index) in rechargeList"
              :key="index"
              class="recharge-item"
              @click="goRechargeDetail(item)"
            >
              <div class="recharge-top">
                <span class="recharge-title">{{ _t18('recharge') }}</span>
                <span class="recharge-amount">+{{ item.amount }} {{ item.coin?.toUpperCase() }}</span>
              </div>
              <div class="recharge-bottom">
                <span class="recharge-time">{{ formatTo12Hour(item.createTime) }}</span>
                <span
                  class="recharge-status"
                  :class="{
                    success: item.status == 1,
                    pending: item.status == 0,
                    failed: item.status != 1 && item.status != 0
                  }"
                >
                {{ item.status == 1 ? _t18('15_success') + ' >' : item.status == 0 ? _t18('15_pending') + ' >' : _t18('15_failed') + ' >' }}

                </span>
              </div>
            </div>
          </template>

          <!-- ✅ 提现 tab：仅改UI，点击固定跳转 withdraw-detail?id=3106 -->
          <template v-else-if="activeTab === 2">
            <div
              v-for="(item, index) in withdrawList"
              :key="index"
              class="withdraw-item"
              @click="goWithdrawDetail(item)"
            >
              <div class="withdraw-top">
                <span class="withdraw-title">{{ _t18('withdraw') }}</span>
                <span class="withdraw-amount">-{{ item.amount }} {{ item.coin?.toUpperCase() }}</span>
              </div>
              <div class="withdraw-bottom">
                <span class="withdraw-time">{{ formatTo12Hour(item.createTime) }}</span>
                <span
                  class="withdraw-status"
                  :class="{
                    success: item.status == 1,
                    pending: item.status == 0,
                    failed: item.status != 1 && item.status != 0
                  }"
                >
                 {{ item.status == 1 ? _t18('15_success') + ' >' : item.status == 0 ? _t18('15_pending') + ' >' : _t18('15_failed') + ' >' }}

                </span>
              </div>
            </div>
          </template>

          <!-- 资金变动等其他 tab：原样保留 -->
          <template v-else>
            <div
              class="record-item"
              v-for="(item, index) in getCurrentList"
              :key="index"
            >
              <div class="record-row">
                <span>{{ _t18('15_currency') }}</span><span>USD</span>
              </div>
              <div class="record-row">
                <span>{{ _t18('15_amount') }}</span>
                <span class="amount">{{ item.amount }}</span>
              </div>
              <div class="record-row">
                <span>{{ _t18('15_outAccount') }}</span>
                <span>{{ safeT18(String(typeConfig[item.transferOutAccount]?.langKey || '')) }}</span>
              </div>
              <div class="record-row">
                <span>{{ _t18('15_inAccount') }}</span>
                <span>{{ safeT18(String(typeConfig[item.transferInAccount]?.langKey || '')) }}</span>
              </div>
              <div class="record-row">
                <span>{{ _t18('15_time') }}</span>
                <span>{{ formatTo12Hour(item.createTime) }}</span>
              </div>
            </div>
          </template>

          <!-- 加载中提示 -->
          <div v-if="loading" class="list-loading">
            <van-loading size="20px" type="spinner" color="#1989fa" />
            <span class="loading-text">{{ _t18('15_loading') }}</span>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user/index'
import { getTransLog } from '@/api/financial/index'
import { getWithdrawList, getRechargeList } from '@/api/account'
import { _t18 } from '@/utils/public'


// ✅ 时间转 12 小时制（支持 "2025-10-30 14:23:45" 这种格式）
function formatTo12Hour(timeStr) {
  if (!timeStr) return '-'
  const match = timeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?/)
  if (!match) return timeStr

  const [, y, m, d, h, min, s = '00'] = match
  const hour = parseInt(h, 10)
  const ampm = hour >= 12 ? 'PM' : 'AM'
  const displayHour = hour % 12 === 0 ? 12 : hour % 12
  return `${y}-${m}-${d} ${displayHour}:${min}:${s} ${ampm}`
}


const router = useRouter()
const activeTab = ref(0)
const listArray = ref([])
const rechargeList = ref([])
const withdrawList = ref([])
const total_zichan = ref(0)
const loading = ref(false)
const finished = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const userStore = useUserStore()

const typeConfig = {
  1: { langKey: '15_type1' },
  2: { langKey: '15_type2' },
  3: { langKey: '15_type3' },
  4: { langKey: '15_type4' },
  5: { langKey: '15_type5' },
  6: { langKey: '15_type6' },
  7: { langKey: '15_type7' },
  8: { langKey: '15_type8' },
  9: { langKey: '15_type9' }
}

const getCurrentList = computed(() => {
  if (activeTab.value === 0) return listArray.value
  if (activeTab.value === 1) return rechargeList.value
  return withdrawList.value
})

const onLoad = async () => {
  if (finished.value) return
  loading.value = true

  try {
    let res = null
    let rows = []

    if (activeTab.value === 0) {
      res = await getTransLog(
        `pageNum=${pageNum.value}&pageSize=${pageSize.value}&userId=${userStore.userInfo.user?.userId}&orderByColumn=createTime&isAsc=desc`
      )
      if (res?.code === 200 || res?.code === '200') rows = res.rows || []
      listArray.value = rows
    } else if (activeTab.value === 1) {
      res = await getRechargeList(`pageNum=${pageNum.value}&pageSize=${pageSize.value}`)
      if (res?.code === 200 || res?.code === '200') rows = res.rows || []
      rechargeList.value = rows
    } else if (activeTab.value === 2) {
      res = await getWithdrawList(`pageNum=${pageNum.value}&pageSize=${pageSize.value}`)
      if (res?.code === 200 || res?.code === '200') rows = res.rows || []
      withdrawList.value = rows
    }

    finished.value = rows.length < pageSize.value
    if (!finished.value) pageNum.value++
  } catch (err) {
    console.error('加载出错:', err)
    finished.value = true
  } finally {
    loading.value = false
  }
}

const change = (val) => {
  activeTab.value = val
  pageNum.value = 1
  finished.value = false
  loading.value = false
  onLoad()
}

onMounted(async () => {
  await userStore.getUserInfo()
  await nextTick()
  const filtered = userStore.userInfo.asset?.filter(i => i.symbol?.toLowerCase() === 'usdt') || []
  const total = filtered.reduce((sum, i) => sum + (i.amount || i.amout || 0), 0)
  total_zichan.value = total
  onLoad()
})

function safeT18(key) {
  // console.log('key:', key, 'type:', typeof key)
  if (!key || typeof key !== 'string') return '-'
  // console.log('1')
  try {
    return _t18(key)
  } catch (e) {
    return '-'
  }
}

// ✅ 新增：跳转到充值详情（保持原逻辑）
function goRechargeDetail(item) {
  const id = item?.id || item?.orderId
  if (!id) return
  router.push(`/recharge-detail?id=${id}`)
}

// ✅ 新增：提现点击固定跳转（按你的要求）
function goWithdrawDetail(item) {
  const id = item?.id || item?.orderId
  if (!id) return
  router.push(`/withdraw-detail?id=${id}`)
}
</script>

<style scoped>
.finance-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f7f8fa;
}

.finance-header {
  flex-shrink: 0;
  background: #f7f8fa;
  position: sticky;
  top: 0;
  z-index: 10;
  padding-bottom: 8px;
}

.finance-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px 16px;
}

.asset-card {
  width: 100%;
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  margin-top: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.asset-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.coin-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e8f8e8;
  padding: 4px;
  margin-right: 10px;
}
.coin-title {
  font-size: 20px;
  font-weight: 700;
  color: #222;
}

.asset-balance {
  display: flex;
  align-items: baseline;
  gap: 12px;
}
.asset-balance .label {
  color: #555;
  font-size: 15px;
}
.asset-balance .value {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: 700;
}
.asset-balance .unit {
  font-size: 14px;
}

.record-section {
  margin-top: 14px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
}

.record-title {
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 12px;
  color: #111;
}

.tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tab-btn {
  flex: 1;
  text-align: center;
  font-size: 15px;
  color: #999;
  padding: 8px 0;
  border-radius: 8px;
  margin: 0 4px;
  position: relative;
  font-weight: 600;
}
.tab-btn.active {
  background: #000;
  color: #fff;
}
.tab-arrow {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: -6px;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #000;
}

.record-list {
  background: #fff;
  border-radius: 8px;
  width: 100%;
}
.record-item {
  padding: 14px 8px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.record-item:first-child {
  border-top: none;
}

.record-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 40px;
  color: #222;
  font-size: 13px;
}
.record-row span:first-child {
  color: #666;
  min-width: 80px;
}
.amount {
  color: #00c693;
  font-weight: 600;
}

/* 空状态 */
.empty-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}
.empty-icon {
  width: 100px;
  margin-bottom: 10px;
}
.empty-text {
  color: #888;
  font-size: 14px;
}

/* 加载中提示 */
.list-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 13px;
  padding: 12px 0;
}
.loading-text {
  margin-left: 6px;
  font-size: 13px;
  color: #666;
}

/* ✅ 充值部分 UI + 点击反馈（保留） */
.recharge-item {
  background: #fff;
  border-radius: 10px;
  padding: 14px 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: background 0.2s;
  cursor: pointer;
}
.recharge-item:active {
  background: #f2f2f2;
}
.recharge-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #111;
}
.recharge-amount {
  color: #00c693;
  font-weight: 700;
}
.recharge-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
  font-size: 13px;
  color: #777;
}
.recharge-status.success {
  color: #00c693;
}
.recharge-status.pending {
  color: #ffaa00;
}
.recharge-status.failed {
  color: #999;
}

/* ✅ 提现列表 UI（新样式，仅UI变化） */
.withdraw-item {
  background: #fff;
  border-radius: 10px;
  padding: 14px 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: background 0.2s;
  cursor: pointer;
}
.withdraw-item:active {
  background: #f2f2f2;
}
.withdraw-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #111;
}
.withdraw-amount {
  color: #ff4d4f;
  font-weight: 700;
}
.withdraw-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
  font-size: 13px;
  color: #777;
}
.withdraw-status.success {
  color: #00c693;
}
.withdraw-status.pending {
  color: #ffaa00;
}
.withdraw-status.failed {
  color: #999;
}
</style>
